package com.colt.contentcenter;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @program: spring-cloud-alibaba-we-chat-app
 * @description: restTemplate传递token
 * @author: colt
 * @create: 2020-09-27 11:46
 **/
public class TestREstTemplateTokenRelayInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        //1.从header获取token
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest servletRequest = servletRequestAttributes.getRequest();
        String token = servletRequest.getHeader("X-Token");
        HttpHeaders headers = request.getHeaders();
        headers.add("X-Token",token);
        //保证请求继续执行
        return execution.execute(request,body);
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("Password123!"));
    }
}
